<!--<template> 
  <el-autocomplete
    class="autocomplete"
    v-model="state.params.search"
    :fetch-suggestions="querySearch"
    popper-class="my-autocomplete"
    placeholder="请输入文章关键字/标签/标题"
    @select="handleSelect"
    @keyup.enter.native="handleSearch"
  >
    <template #suffix>
      <el-icon class="el-input__icon" @click="handleIconClick">
        <search />
      </el-icon>
    </template>
    <template #default="{ item }">
      <div v-if="item.key" class="history_head">
        <div class="history">
          <span>搜索历史</span>
          <el-button key="清空" type="primary" link>清空</el-button>
        </div>
      </div>
      <span class="content">{{ item.content }}</span>
    </template>
  </el-autocomplete>
</template>

 <script lang="ts" setup>

import { ElMessage } from "element-plus"
import { onMounted, onUpdated, reactive, ref } from "vue"
import { useRouter,useRoute } from 'vue-router'
import { Search } from "@element-plus/icons-vue";
import {GetArticleList} from '../api/api'
import { useStore } from "vuex"
const emit = defineEmits(['emitSearch'])
interface LinkItem {
  value: string;
  link: string;
}
const store=useStore()
const router=useRouter()
const route=useRoute()
const state=reactive({
    params: {
    search:"",
    author: "",
    keyword: "",
    likes: "", // 是否是热门文章
    state: 1, // 文章发布状态 => 0 草稿，1 已发布,'' 代表所有文章
    tag_id: "",
    category_id: "",
    pageNum: 1,
    pageSize: 10,
  }
})
const links = ref<LinkItem[]>([]);

const querySearch = (queryString: string, cb) => {
  console.log("qS:",queryString)
  const results = queryString
    ? links.value.filter(createFilter(queryString))
    : links.value;
  // call callback function to return suggestion objects
  cb(results);
};
const createFilter = (queryString) => {
  
  return (restaurant) => {
    console.log(restaurant)
    return (
       restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    );
  };
};
const loadAll = () => {
  return [
    { key: 1 },
    { value: "vue", content: "https://github.com/vuejs/vue" },
    { value: "element", content: "https://github.com/ElemeFE/element" },
    { value: "cooking", content: "https://github.com/ElemeFE/cooking" },
    { value: "mint-ui", content: "https://github.com/ElemeFE/mint-ui" },
    { value: "vuex", content: "https://github.com/vuejs/vuex" },
    { value: "vue-router", content: "https://github.com/vuejs/vue-router" },
    { value: "babel", content: "https://github.com/babel/babel" },
  ];
};
const handleSelect = (item: LinkItem) => {
  console.log(item);
};

const handleIconClick = (ev: Event) => {
  console.log(ev);
};

const handleSearch=async ():Promise<void>=>{
     
     console.log("回车了~~")
     store.commit('setSeaContent',state.params.search)
     store.commit('setIsSearch',true)
     if(route.path!=='/articles'&&route.path!=='/my'){
      router.push("/articles")
     }else if(route.path==='/articles'){ 
      store.commit('setIsAritcles',true)
     }else{
      store.commit('setIsMy',true)
     }
    // //  console.log(route.path)
    //  if(route.path!='/my'){
    // //  const res = await GetArticleList(state.params);
    //    router.push('/articles')
    //    emit("emitSearch",state.params.search)
    //  }else{
    //    if (!localStorage.getItem("userInfo")) {
    //     ElMessage({
    //      message: "请先登录!",
    //      type: "warning",
    //     });
    //   return;
    // }
    // state.params.author = JSON.parse(localStorage.getItem("userInfo")).name;

    //  }
    // const res = await GetArticleList(state.params);
    // console.log("res:",res);
}

onMounted(() => {
   links.value = loadAll();
});
</script>

<style  lang="less">
.history_head .history{
    display: flex;
    justify-content: space-between;
    cursor:default;
}
.el-input__icon{
  cursor: pointer;
}
</style>-->

<template>
  <el-autocomplete
    v-model="state.params.search"
    :fetch-suggestions="querySearch"
    popper-class="my-autocomplete"
    placeholder="Please input"
    @select="handleSelect"
    @keyup.enter.native="handleSearch"
  >
    <template #suffix>
      <el-icon class="el-input__icon" @click="handleIconClick">
        <search />
      </el-icon>
    </template>

    <template #default="{ item }">
      <div v-if="item.flag === 0" class="history_head">
        <div class="history">
          <span>搜索历史</span>
          <el-button key="清空" type="primary" link @click="clearHistory()">清空</el-button>
        </div>
      </div>
      <!-- <span class="content">{{ item.content }}</span> -->
      <div v-else class="value">{{ item.value }}</div>
      <!-- <span class="link">{{ item.link }}</span> -->
    </template>
  </el-autocomplete>
</template>

<script lang="ts" setup>
import { Edit } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
import { onMounted, onUpdated, reactive, ref } from "vue"
import { useRouter,useRoute } from 'vue-router'
import { Search } from "@element-plus/icons-vue";
import {GetArticleList} from '../api/api'
import { useStore } from "vuex"
const emit = defineEmits(['emitSearch'])
interface LinkItem {
  value: string
  link: string
}
const store=useStore()
const router=useRouter()
const route=useRoute()
const state=reactive({
    historyList:[],
    params: {
    search:"",
    author: "",
    keyword: "",
    likes: "", // 是否是热门文章
    state: 1, // 文章发布状态 => 0 草稿，1 已发布,'' 代表所有文章
    tag_id: "",
    category_id: "",
    pageNum: 1,
    pageSize: 10,
  }
})

const links = ref<LinkItem[]>([])

const querySearch = (queryString: string, cb) => {
  const results = queryString
    ? links.value.filter(createFilter(queryString))
    : links.value
  // call callback function to return suggestion objects
  cb(results)
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}
// const loadAll = () => {
//   return [
//     {flag:1, value: 'vue' },
//     {flag:1 ,value: 'element'},
//     {flag:1,value: 'cooking'},
//     {flag:1, value: 'mint-ui'},
//     // {key:5, value: 'vuex'},
//     // {key:6, value: 'vue-router'},
//     // {key:7,value: 'babel'},
//   ]
// }
const handleSelect = (item: LinkItem) => {
  console.log(item)
}

const handleIconClick = (ev: Event) => {
  console.log(ev)
}
const handleSearch=async ():Promise<void>=>{
     console.log("回车了~~")
     saveHistory(state.params.search)
     store.commit('setSeaContent',state.params.search)
     store.commit('setIsSearch',true)
     if(route.path!=='/articles'&&route.path!=='/my'){
      router.push("/articles")
     }else if(route.path==='/articles'){
      store.commit('setIsAritcles',true)
     }else{
      store.commit('setIsMy',true)
     }
    // //  console.log(route.path)
    //  if(route.path!='/my'){
    // //  const res = await GetArticleList(state.params);
    //    router.push('/articles')
    //    emit("emitSearch",state.params.search)
    //  }else{
    //    if (!localStorage.getItem("userInfo")) {
    //     ElMessage({
    //      message: "请先登录!",
    //      type: "warning",
    //     });
    //   return;
    // }
    // state.params.author = JSON.parse(localStorage.getItem("userInfo")).name;

    //  }
    // const res = await GetArticleList(state.params);
    // console.log("res:",res);
}
const saveHistory=(content)=>{
        	if(content === ''){
        		// this.$toast('请输入搜索内容');
        		return ;
        	}else{
             for(let i=0;i<state.historyList.length;i++){
                       if(state.historyList[i].value===content){
                            state.historyList.splice(i,1)
                            state.historyList.splice(1,0,{flag:1,value:content})
                            localStorage.setItem("historyList", JSON.stringify(state.historyList));
                            return;
                       }
             }
             if(!state.historyList.length)  {
              state.historyList.push({flag:0,value:''})
             }
              state.historyList.push({flag:1,value:content})
              //大于8个删除第一个
              if(state.historyList.length>9){state.historyList.splice(1,1)}
             localStorage.setItem("historyList", JSON.stringify(state.historyList));
            //  state.historyList.forEach(item=>{
            //    if(item.value===content){
            //     state.historyList.
            //    }
            //  })
          //  if (!state.historyList.includes(this.search_val)) {
          //         this.historyList.unshift(this.search_val);
          //         localStorage.setItem("historyList", JSON.stringify(this.historyList));
          //       }else{
          //           //有搜索记录，删除之前的旧记录，将新搜索值重新push到数组首位
          //           let i =this.historyList.indexOf(this.search_val);
          //           this.historyList.splice(i,1)
          //           this.historyList.unshift(this.search_val);
          //           localStorage.setItem("historyList", JSON.stringify(this.historyList));
          //       }
          }

}
const clearHistory=()=>{
      localStorage.removeItem('historyList')
      state.historyList=[]
}
onMounted(() => {
   if (JSON.parse(localStorage.getItem("historyList"))) {
            state.historyList = JSON.parse(localStorage.getItem("historyList"));
        }    
    links.value =state.historyList
})
</script>

<style>
.history_head .history {
  display: flex;
  justify-content: space-between;
  cursor: default;
}
.el-input__icon {
  cursor: pointer;
}
</style>
